package threadcoreknowledge.createthread.threadobjectclasscommommethods;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class ProduceConsumerModel {

    public static void main(String[] args) {
        EventStorage eventStorage = new EventStorage();
        Producer producer = new Producer(eventStorage);
        Consumer consumer = new Consumer(eventStorage);

        new Thread(producer).start();
        new Thread(consumer).start();


    }
}
class Producer implements Runnable{
    private EventStorage storage;

    public Producer(EventStorage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            storage.put();
        }
    }
}
class Consumer implements Runnable{
    private EventStorage storage;

    public Consumer(EventStorage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            storage.take();
        }
    }
}

class EventStorage{
    private int maxSize;
    private LinkedList<Date> storage;

    public EventStorage(){
        maxSize = 10;
        storage = new LinkedList<>();
    }

    public synchronized void put(){

        //队列中产品已经满了，就停止输送
        while (storage.size() == maxSize){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //往队列中添加产品
        storage.add(new Date());
        System.out.println("仓库里有了"+storage.size()+"个产品");

        //放好之后就去通知别人
        notify();

    }


    public synchronized void take(){

        //队列中的东西已经没了，就停止获取
        while (storage.size() == 0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("拿到了"+storage.poll()+"，现在仓库还剩下"+storage.size()+"个产品");
        //前面这段代码能执行，说明队列仓库里面还有东西，那么就要唤醒它继续去取东西
        notify();
    }





}
